package com.tfswue.qmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfswue.qmp.entity.User1;
import com.tfswue.qmp.service.User1Sesrvice;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api/users")

@Tag(name = "用户接口",description = "符合Restful风格的用户接口")

public class RestFulUserController {
    @Autowired
    private User1Sesrvice user1Sesrvice;
    //用get方式查询所有用户

    @Operation(summary = "查询所有用户",description = "查询所有用户")

    @GetMapping

    @ApiResponse(responseCode = "200",description = "查询所有用户返回用户list")

    public List<User1> getAllUsers() {
        return user1Sesrvice.list();
    }
    //根据ID，查询单个用户

    @Cacheable(value = "dataCache",key = "#id")     //缓存

    @GetMapping("/{id}/{name}")
    public User1 getUserById(@Parameter(description = "用户id",required = true) @PathVariable("id") Integer id, @PathVariable("name")String name) {
        log.error("id:{},name:{}",id,name);
        return user1Sesrvice.getById(id);
    }
    //用get方式分页查询所有用户,{page}/{size}参数：页码，每页记录数
    @GetMapping("/querypage/{page}/{size}")
    public List<User1> queryPage(@PathVariable("page") Integer page,@PathVariable("size") Integer size) {
        Page<User1> testpage = new Page<>(page,size);
        Page<User1> user1Page = user1Sesrvice.page(testpage, null);
       return user1Page.getRecords();
    }

    //进行多条件分页查询
    @GetMapping("/querylist/{page}/{size}")
    public List<User1> queryList(@PathVariable("page") Integer page,
                                 @PathVariable("size") Integer size,
                                 @RequestBody User1 user1) {

        QueryWrapper<User1> queryWrapper = new QueryWrapper<>();
        if (user1.getUsername() != null) {
            queryWrapper.like("username",user1.getUsername());
        }
        if(user1.getEmail() != null){
            queryWrapper.like("email",user1.getEmail());
        }


        Page<User1> testpage = new Page<>(page,size);
        Page<User1> user1Page = user1Sesrvice.page(testpage, null);
        return user1Page.getRecords();
    }

    //添加用户
    @PostMapping
    public boolean addUser(@RequestBody User1 user1) {
        return user1Sesrvice.save(user1);
    }

    //修改用户
    @PutMapping
    public boolean updateUser(@RequestBody User1 user1) {
        return user1Sesrvice.updateById(user1);
    }

    //删除用户
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable("id") Integer id) {
        return user1Sesrvice.removeById(id);
    }


}
